<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>角色管理</span>
        <el-button type="primary" style="float: right" @click="handleAdd">新增角色</el-button>
      </div>
    </template>
    <el-table :data="roleList" stripe border fit>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column label="权限">
        <template #default="scope">
          <el-tag v-for="pid in scope.row.permissionIds" :key="pid" style="margin-right:4px">
            {{ getPermissionName(pid) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" title="角色信息">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="权限分配">
          <el-checkbox-group v-model="formData.permissionIds">
            <el-checkbox v-for="p in permissionList" :key="p.id" :label="p.id">{{ p.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRole">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
const roleList = ref([])
const permissionList = ref([])
const dialogVisible = ref(false)
const formData = reactive({ id: null, name: '', permissionIds: [] })
const fetchData = async () => {
  roleList.value = await request.get('/roles')
  permissionList.value = await request.get('/permissions')
}
onMounted(fetchData)
const handleAdd = () => {
  formData.id = null
  formData.name = ''
  formData.permissionIds = []
  dialogVisible.value = true
}
const handleEdit = (row) => {
  formData.id = row.id
  formData.name = row.name
  formData.permissionIds = [...row.permissionIds]
  dialogVisible.value = true
}
const saveRole = async () => {
  if (formData.id) {
    await request.put(`/roles/${formData.id}`, formData)
  } else {
    await request.post('/roles', formData)
  }
  dialogVisible.value = false
  fetchData()
}
const handleDelete = async (row) => {
  await request.delete(`/roles/${row.id}`)
  fetchData()
}
const getPermissionName = (pid) => {
  const p = permissionList.value.find(p => p.id === pid)
  return p ? p.name : ''
}
</script>
<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 